<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .message{
            height: 300px;
            width: 100%;
            border: 1px solid #dddddd;
        }
    </style>
</head>
<body>
<div class="message" id="message"></div>
<div>
    <label for="txt"></label><input type="text" placeholder="请输入" id="txt">
    <input type="button" value="发送" onclick="sendMessage()">
    <input type="button" value="断开连接" onclick="closeOnn()">
</div>
<script>
    socket = new WebSocket("ws://127.0.0.1:8000/room/{{ num }}/")
    {#创建好连接后自动触发(握手环节,服务端执行self.accept())#}
    socket.onopen = function(event){
        let lag = document.createElement("div")
        lag.innerText = "[websocket连接成功]"
        document.getElementById("message").appendChild(lag)
    }
    {#发数据#}
    function sendMessage(){
        var txt = document.getElementById("txt")
        console.log(txt.value)
        socket.send(txt.value)
    }
    {#收数据#}
    socket.onmessage = function (event){
        var data = event.data
        console.log("客户端接收到消息-->",data)
        let lag = document.createElement("div")
        lag.innerText = data
        document.getElementById("message").appendChild(lag)
    }
    {#服务器主动断开连接,触发#}
    socket.onclose = function (event){

    }
    function closeOnn(){
        socket.close()
    }
</script>
</body>
</html>